/* import {
	wxappReAuth,
	getUser,
	bindingPhone,
	wxappAuth,
	postUserEdit,
	bindGuideUser
} from "@/api/user";
import store from "../store";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie.js";
import {
	getStorage,
} from "@/utils/storage";
import stringify from "@/utils/querystring"; */

export function dataFormat(time, option) {
	if (option) {
		time = +time * 1000;
	}
	const d = new Date(time);
	const now = new Date().getTime();

	const diff = (now - d) / 1000;
	if (diff < 30) {
		return "刚刚";
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + "分钟前";
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + "小时前";
	} else if (diff < 3600 * 24 * 2) {
		return "1天前";
	}
	if (option) {
		// return parseTime(time, option);
	} else {
		let timeStr = d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日" + d.getHours() + "时" + d
			.getMinutes() + "分"
		return timeStr
	}
}

export function dataFormatT(time) {
	time = +time * 1000;
	const d = new Date(time);

	return (
		d.getFullYear() +
		"/" +
		(d.getMonth() + parseInt(1)) +
		"/" +
		d.getDate()
	);
}

export function trim(str) {
	return String.prototype.trim.call(str);
}

export function isType(arg, type) {
	return Object.prototype.toString.call(arg) === "[object " + type + "]";
}

export function isWeixin() {
	// return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
	return false
}

export function parseQuery() {
	var pages = getCurrentPages() //获取加载的页面
	var currentPage = pages[pages.length - 1] //获取当前页面的对象
	var url = currentPage.route //当前页面url
	var options = currentPage.options //如果要获取url中所带的参数可以查看options
	return options
}



/*获取当前页带参数的url*/
export function getCurrentPageUrlWithArgs() {
	var pages = getCurrentPages() //获取加载的页面
	var currentPage = pages[pages.length - 1] //获取当前页面的对象
	var url = currentPage.route //当前页面url
	var options = currentPage.options //如果要获取url中所带的参数可以查看options

	//拼接url的参数
	var urlWithArgs = url + '?'
	for (var key in options) {
		var value = options[key]
		urlWithArgs += key + '=' + value + '&'
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

	return urlWithArgs
}

// 复制到剪切板
export const copyClipboard = (data) => {
	uni.setClipboardData({
		data: data,
		success: (res) => {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
				duration: 2000
			})
		},
		fail: (err) => {
			console.log(err, '失败内容=====')
		}
	})
}


export const toAuthorization = (msg) => {
	wx.hideLoading();
	wx.showToast({
		title: msg,
		icon: 'none',
		duration: 2000
	});
	// console.log(222222222)
	replace({
		path: '/pages/poorNetwork/main',
		query: {
			redirect: `/${getCurrentPageUrl()}`,
			...parseQuery()
		}
	})
}


export const login = (option) => {
	return new Promise((resolve, reject) => {
		// 通过公众号跳转到小程序会带公众号appid和公众号用户openid参数，传入后台保存公众号用户与小程序用户关系
		let mpAppid = option.mpAppid ? option.mpAppid : '',
			mpOpenid = option.mpOpenid ? option.mpOpenid : '';
		wx.login({
			success: res => {
				let code = res.code;
				store.commit("UPDATE_WXCODE", res.code);
				if (code) {
					wxappAuth({
						code: code,
						spread: cookie.get("spread"),
						// 通过公众号跳转到小程序会带公众号appid和公众号用户openid参数，传入后台保存公众号用户与小程序用户关系
						mpAppid: mpAppid,
						mpOpenid: mpOpenid,
						taskId: option.rewardId
					}).then(({
						data
					}) => {
						// 如果用户已经授权过，更新一下用户信息
						resolve(data)
						wx.hideLoading();
						store.commit('setIsMock', data.isMock);
						store.commit("LOGIN", data.token, dayjs(data.expires_time));
						store.commit("SET_SUB_MSG_TEMPLATES", data.subMsg);
						getUser().then(res => {
							store.dispatch('changeUserInfo', {
								user: res.data
							});
							// 如果有用户头像和昵称，设置用户缓存信息
							if (res.data.avatar && res.data.nickname) {
								store.commit("UPDATE_USERINFO", res.data);
								uni.setStorageSync("hasUserInfo", true);
							} else if (!res.data.avatar && !res.data.nickname) {
								store.commit("UPDATE_USERINFO", res.data);
								uni.removeStorageSync("hasUserInfo", true);
							}
							let url = "/pages/launch/main?type=index";
							// 新的首页
							// url = "/pages/main/index";
							// 通过用户邀请进入小程序，绑定上下级关系
							if (option.rewardId && option.shareUid) {
								url =
									`/pages/launch/main?type=index&uid=${option.spread}&channel=${option.channelId}`;
							}
							if (option.forward) {
								url = decodeURIComponent(option.forward)
								// 如果扫导购员的码进来需要绑定
								if (url.indexOf("qrcodeFlag=1") > -1) {
									bindGuideUser({
										spreadUid: option.spread
									}).then(res => {
										console.log("导购员绑定成功");
									})
								}
							}
							if (option.spread) {
								if (url.indexOf('?') > -1) {
									url += '&'
								} else {
									url += '?'
								}
								url += 'spread=' + option.spread
							};
							replace({
								path: url
							});
						}).catch(() => {
							reject()
							option && option.fail ?
								option.fail() :
								toAuthorization('获取用户信息失败');
						});
					}).catch(() => {
						reject();
						option && option.fail ?
							option.fail() :
							toAuthorization('login接口调用错误')
					});
				} else {
					reject()
					option && option.fail ?
						option.fail() :
						toAuthorization('微信官方login接口调用无code')
				}
			},
			fail: () => {
				reject()
				option && option.fail ? option.fail() : toAuthorization('微信官方login接口调用失败')
			}
		});
	})
}

export function getQueryObject(url) {
	let ret = {};
	let index = url.indexOf('?');
	if (index < 0) return ret;
	let query = url.substr(index + 1)
	console.log('query', query)
	if (!query) return ret;
	let arr = query.split('&')
	console.log('arr', arr)
	if (arr.length == 0) return ret;
	for (let p of arr) {
		let vals = p.split('=')
		if (vals.length == 0) continue
		ret[vals[0]] = vals[1]
	}
	console.log('queryObj', ret)
	return ret
}

export function parseUrl(location) {
	if (typeof location === 'string') return location

	const {
		path,
		query
	} = location
	const queryStr = stringify(query)

	if (!queryStr) {
		return path
	}

	return `${path}?${queryStr}`
}

export function parseRoute($mp) {
	const _$mp = $mp || {}
	const path = _$mp.page && _$mp.page.route
	return {
		path: `/${path}`,
		params: {},
		query: _$mp.query,
		hash: '',
		fullPath: parseUrl({
			path: `/${path}`,
			query: _$mp.query
		}),
		name: path && path.replace(/\/(\w)/g, ($0, $1) => $1.toUpperCase())
	}
}

export function push(location, complete, fail, success) {
	let path = ''
	if (typeof location === 'string') {
		path = location
	} else {
		path = location.path
	}
	console.log(path)
	if (path != '/pages/launch/main' || path != '/pages/Loading/index') {
		if (!store.getters.userInfo.uid) {
			// replace({ path: '/pages/authorization/main', query: { redirect: `/${getCurrentPageUrl()}`, ...parseQuery() } })
			// return
		}
	}
	const url = parseUrl(location)
	const params = {
		url,
		complete,
		fail,
		success
	}

	if (location.isTab) {
		wx.switchTab(params)
		return
	}
	if (location.reLaunch) {
		wx.reLaunch(params)
		return
	}
	wx.navigateTo(params)
}

export function replace(location, complete, fail, success) {
	const url = parseUrl(location)
	wx.redirectTo({
		url,
		complete,
		fail,
		success
	})
}

export function go(delta) {
	wx.navigateBack({
		delta
	})
}

export function back() {
	wx.navigateBack({
		delta: 1,
		success: function(e) {},
		fail: function(e) {}
	})
}


export function handleQrCode() {
	console.log('mounted========================parseQuery()', parseQuery())

	var urlSpread = parseQuery()["q"];
	if (urlSpread) {
		// 通过海报二维码进来
		urlSpread = urlSpread
			.split("%3F")[1]
			.replace(/%3D/g, ":")
			.replace(/%26/g, ",")
			.split(",")
			.map((item, index) => {
				item = item.split(":");
				return `"${item[0]}":"${item[1]}"`;
			})
			.join(",");
		urlSpread = JSON.parse("{" + urlSpread + "}");
		return urlSpread
	}
	return null
}

const getImageInfo = (images) => {
	console.log(images)
	return new Promise((resolve, reject) => {
		let imageAry = {}
		images.map((item, index) => {
			wx.getImageInfo({
				src: item,
				fail: function(res) {
					imageAry[index] = null
					console.log(res)
					if (imageAry.length == images.length) {
						resolve(imageAry)
					}
				},
				success: function(res) {
					imageAry[index] = res
					console.log(res)
					if (imageAry.length == images.length) {
						resolve(imageAry)
					}
				}
			})
		})
	})
}


/**
 * 获取分享海报
 * @param array store 海报素材
 * @param string store_name 素材文字
 * @param string price 价格
 * @param function successFn 回调函数
 *
 *
 */
export const PosterCanvas = (store, successCallBack) => {
	wx.showLoading({
		title: '海报生成中',
		mask: true
	});
	getImageInfo([store.image, store.code]).then(res => {
		let contentHh = 48 * 1.3
		const ctx = wx.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		const WIDTH = 747
		const HEIGHT = 1326;
		ctx.fillStyle = "#FFFFFF";
		ctx.fillRect(0, 0, WIDTH, HEIGHT);
		ctx.drawImage(res[1].path, 40, 1064, 200, 200);
		ctx.drawImage(res[0].path, 0, 0, WIDTH, WIDTH);
		ctx.save();
		let r = 90;
		let d = r * 2;
		let cx = 40;
		let cy = 990;
		ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
		ctx.clip();
		ctx.restore();
		// ctx.setTextAlign('center');
		ctx.setFontSize(48);
		ctx.setFillStyle('#000');
		// 文字换行
		let chr = store.title.split("")
		console.log("获取到的文字啊-----------------------------------", store.title)
		let temp = ""
		let row = []
		for (var a = 0; a < chr.length; a++) {
			if (ctx.measureText(temp).width < WIDTH - 60) {
				temp += chr[a];
			} else {
				a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
				row.push(temp);
				temp = "";
			}
		}
		row.push(temp);
		//如果数组长度大于2 则截取前两个
		//如果数组长度大于3 则截取前三个
		if (row.length > 2) {
			var rowCut = row.slice(0, 2);
			var rowPart = rowCut[1];
			var test = "";
			var empty = [];
			for (var a = 0; a < rowPart.length; a++) {
				if (ctx.measureText(test).width < WIDTH - 60) {
					test += rowPart[a];
				} else {
					break;
				}
			}
			empty.push(test);
			var group = empty[0] + "..." //这里只显示两行，超出的用...表示
			rowCut.splice(1, 1, group);
			row = rowCut;
		}
		for (let b = 0; b < 2; b++) {
			if (b < row.length) {
				ctx.fillText(row[b], 30, 780 + contentHh + (b + 1) * 60, WIDTH - 60); //每行字体y坐标间隔60
			}
		}
		// ctx.fillText(store.title, WIDTH / 2, 810 + contentHh);
		ctx.setTextAlign('center')
		ctx.setFontSize(32);
		ctx.setFillStyle('red');
		ctx.fillText('￥' + store.price, WIDTH / 2, 950 + row.length * 60);
		ctx.setTextAlign('center')
		ctx.setFontSize(22);
		ctx.setFillStyle('#333333');
		ctx.fillText('长按识别二维码立即购买', WIDTH / 2, 1167);
		// ctx.drawImage(store.code, 199, 1064, 200, 200);

		ctx.save();
		ctx.draw(true, function(oi) {
			wx.canvasToTempFilePath({
				canvasId: 'myCanvas',
				fileType: 'png',
				destWidth: WIDTH,
				destHeight: HEIGHT,
				success: function(res) {
					// console.log(res,"successCallBack(res.tempFilePath);")
					wx.hideLoading();
					successCallBack && successCallBack(res.tempFilePath);
				},
				fail: function(error) {
					console.log(error)
				},
			})
		});
	})
}
/* 模版订阅通知 */
export const requestSubscribeMessage = ids => {
	return new Promise((resolve, reject) => {
		if (!ids || ids.length == 0) resolve({});
		let filteredIds = ids.filter(item => item != undefined && item != null && item != '');
		if (filteredIds.length == 0) resolve({});
		wx.requestSubscribeMessage({
			tmplIds: filteredIds,
			success(res) {
				resolve(res)
			},
			fail(err) {
				console.log(err)
				resolve({})
			}
		})
	});
}
//判断用户是否登录
export const checkAuthentication = () => {
	return new Promise((resolve, reject) => {
		let hasUserInfo = uni.getStorageSync("hasUserInfo");
		if (hasUserInfo) {
			resolve();
		} else {
			reject({
				loginStatus: "0"
			});
		}
	})
}

/**
 * 更新后台用户信息
 * 先校验sessionKey是否过期，如果过期，重新登录获取code更新sessionKey后再更新
 * @param {*} data {iv: '', encryptedData: ''}
 */
export const updateUserInfo = (data) => {
	return new Promise((resolve, reject) => {
		// session是否过期
		wx.checkSession({
			// session没有过期，直接更新用户信息
			success() {
				postUserEdit(data).then((res) => {
					resolve(res);
				}).catch((err) => {
					resolve(err);
				})
			},
			// session已经过期，重新登陆，需要重新获取用户信息的加密数据，因为上次获取的加密数据是用已经过期的sessionKey加密的，会解密失败
			fail() {
				wx.login({
					success(res) {
						if (res.code) {
							wxappReAuth({
								code: res.code
							}).then(() => {
								postUserEdit({
									encryptedData: data.encryptedData,
									iv: data.iv
								}).then((Res) => {
									resolve(Res);
								}).catch((Err) => {
									resolve(Err);
								})
							})
						} else {
							console.error('登录失败！')
							console.error(res)
							resolve()
						}
					},
					fail(err) {
						console.error(err)
						resolve()
					}
				})
			}
		})
	});
}

export const updatePhoneNumber = (data) => {
	return new Promise((resolve, reject) => {
		//校验是否过期
		wx.checkSession({
			success() {
				bindingPhone(data).then((res) => {
					resolve();
				}).catch(err => {
					if (err.msg == "您的账号已经绑定过手机号码") {
						resolve();
					}
				})
			},
			fail() {
				// session_key 已经失效，需要重新执行登录流程
				wx.login({
					success(loginRes) {
						bindingPhone({
								code: loginRes.code,
								encryptedData: data.encryptedData,
								iv: data.iv
							})
							.then(res => {
								resolve();
								wx.hideLoading();
							})
							.catch(error => {
								wx.showToast({
									title: error.msg || error.response.data.msg,
									icon: "none",
									duration: 2000
								});
								reject();
							});
					}
				});
			}
		})
	})
}

// 数字转汉字
export const numberToChinaNum = (num) => {
	var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千',
		'亿'); //可继续追加更高位转换值
	if (!num || isNaN(num)) {
		return "零";
	}
	var english = num.toString().split("")
	var result = "";
	for (var i = 0; i < english.length; i++) {
		var des_i = english.length - 1 - i; //倒序排列设值
		result = arr2[i] + result;
		var arr1_index = english[des_i];
		result = arr1[arr1_index] + result;
	}
	//将【零千、零百】换成【零】 【十零】换成【十】
	result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
	//合并中间多个零为一个零
	result = result.replace(/零+/g, '零');
	//将【零亿】换成【亿】【零万】换成【万】
	result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
	//将【亿万】换成【亿】
	result = result.replace(/亿万/g, '亿');
	//移除末尾的零
	result = result.replace(/零+$/, '')
	//将【零一十】换成【零十】
	//result = result.replace(/零一十/g, '零十');
	//貌似正规读法是零一十
	//将【一十】换成【十】
	result = result.replace(/^一十/g, '十');
	return result;
}

// 字符串加密
export const toEnCode = (str) => {
	//定义密钥
	var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var kleng = key.length; //获取密钥的长度
	var a = key.split(""); //把密钥字符串转换为字符数组
	var s = "",
		b, b1, b2, b3; //定义临时变量
	for (var i = 0; i < str.length; i++) { //遍历字符串
		b = str.charCodeAt(i); //逐个提取每个字符，并获取Unicode编码值
		b1 = b % kleng; //求Unicode编码值得余数
		b = (b - b1) / kleng; //求最大倍数
		b2 = b % kleng; //求最大倍数的于是
		b = (b - b2) / kleng; //求最大倍数
		b3 = b % kleng; //求最大倍数的余数
		s += a[b3] + a[b2] + a[b1]; //根据余数值映射到密钥中对应下标位置的字符
	}
	return s; //返回这些映射的字符
}

// 字符串解密
export const toDeCode = (str) => {
	//定义密钥
	var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var kleng = key.length; //获取密钥的长度
	var b, b1, b2, b3, d = 0,
		s; //定义临时变量
	s = new Array(Math.floor(str.length / 3)); //计算加密字符串包含的字符数，并定义数组
	b = s.length; //获取数组的长度
	for (var i = 0; i < b; i++) { //以数组的长度循环次数，遍历加密字符串
		b1 = key.indexOf(str.charAt(d)); //截取周期内第一个字符串，计算在密钥中的下标值
		d++;
		b2 = key.indexOf(str.charAt(d)); //截取周期内第二个字符串，计算在密钥中的下标值
		d++;
		b3 = key.indexOf(str.charAt(d)); //截取周期内第三个字符串，计算在密钥中的下标值
		d++;
		s[i] = b1 * kleng * kleng + b2 * kleng + b3 //利用下标值，反推被加密字符的Unicode编码值
	}
	b = eval("String.fromCharCode(" + s.join(',') + ")"); // 用fromCharCode() 算出字符串
	return b; //返回被解密的字符串
}
// 防抖
export const debounce = (fn, delay, immediate = false) => {
	// 1.定义一个定时器, 保存上一次的定时器
	let timer = null
	let isInvoke = false
	// 2.真正执行的函数
	const _debounce = function(...ages) {
		// 取消上一次的定时器
		if (timer) clearTimeout(timer)

		// 判断是否需要立即执行
		if (immediate && !isInvoke) {
			fn.apply(this, ages)
			isInvoke = true
		} else {
			// 延迟执行
			timer = setTimeout(() => {
				// 外部传入的真正要执行的函数
				fn.apply(this, ages)
				isInvoke = false
			}, delay)
		}
	}
	return _debounce
}
// 节流
export const throttle = (func, delay) => {
	let sign = true;
	return function() {
		// 在函数开头判断标志是否为 true，不为 true 则中断函数
		if (!sign) return;
		//  sign 设置为 false，防止执行之前再被执行
		sign = false;
		setTimeout(() => {
			func.apply(this, arguments)
			// 执行完事件之后，重新将这个标志设置为 true
			sign = true;
		}, delay)
	}
}
export {
	getCurrentPagePath
}
from './getCurrentPagePath'